#include "sizehandle.h"

#include <QPainter>

SizeHandlePrivate::SizeHandlePrivate(int dir)
    : m_dir(dir)
    , m_center(0, 0)
    , m_sideLength(8)
{

}

SizeHandle::SizeHandle(int point, QObject *parent)
    : QObject(parent)
    , d_ptr(new SizeHandlePrivate(point))
{

}

SizeHandle::SizeHandle(const SizeHandle &sh, QObject *parent)
    : QObject(parent)
    , d_ptr(new SizeHandlePrivate(sh.direction()))
{
    if (this == &sh)
        return;

    setDirection(sh.direction());
    setCenter(sh.center());
    setSideLength(sh.sideLength());
}

SizeHandle &SizeHandle::operator=(const SizeHandle &sh)
{
    if (this == &sh)
        return *this;
    setDirection(sh.direction());
    setCenter(sh.center());
    setSideLength(sh.sideLength());

    return *this;
}

int SizeHandle::direction() const
{
    if (d_ptr)
        return d_ptr->m_dir;

    return Handle_None;
}

void SizeHandle::setDirection(int dir)
{
    if (d_ptr)
    {
        d_ptr->m_dir = dir;
    }
}

void SizeHandle::setCenter(const QPoint &center)
{
    if (d_ptr)
    {
        d_ptr->m_center = center;
    }
}

QPoint SizeHandle::center() const
{
    QPoint pt;
    if (d_ptr)
    {
        pt = d_ptr->m_center;
    }

    return pt;
}

void SizeHandle::setSideLength(int len)
{
    if (d_ptr)
    {
        d_ptr->m_sideLength = len;
    }
}

int SizeHandle::sideLength() const
{
    int len = 0;
    if (d_ptr)
    {
        len = d_ptr->m_sideLength;
    }

    return len;
}

void SizeHandle::paint(QPainter *painter)
{
    if (painter && d_ptr)
    {
        painter->save();
        painter->setRenderHint(QPainter::Antialiasing);
        QPen pen = painter->pen();
        pen.setBrush(QBrush(Qt::white));
        pen.setWidth(g_penWidth);
        painter->setPen(pen);
        QBrush brush = painter->brush();
        brush.setColor(Qt::blue);
        painter->setBrush(brush);
        QPainterPath path;
        path.addEllipse(rect());
        painter->fillPath(path, QBrush(Qt::blue));
        painter->drawEllipse(rect());

        painter->restore();
    }
}

bool SizeHandle::containsPoint(const QPoint &pt) const
{
    return rect().contains(pt);
}

QRectF SizeHandle::rect() const
{
    QRectF rectf;
    if (d_ptr)
    {
        rectf.setTopLeft(QPoint(d_ptr->m_center.x()-(d_ptr->m_sideLength/2), d_ptr->m_center.y()-(d_ptr->m_sideLength/2)));
        rectf.setSize(QSize(d_ptr->m_sideLength, d_ptr->m_sideLength));
    }

    return rectf;
}
